package com.yanjue.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanjue.common.constant.HomePageConstant;
import com.yanjue.common.entity.IndexBooklist;
import com.yanjue.common.enums.BooklistMoreTypeEnum;
import com.yanjue.common.redisKey.RedisExpire;
import com.yanjue.common.redisKey.RedisHomepageKey;
import com.yanjue.common.redisKey.RedisService;
import com.yanjue.mapper.IndexBooklistMapper;
import com.yanjue.service.IndexBooklistItemService;
import com.yanjue.service.IndexBooklistService;
import com.yanjue.vo.BooklistBookVO;
import com.yanjue.vo.IndexBooklistVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
* @author yanju
* @description 针对表【index_booklist(精品页书单配置)】的数据库操作Service实现
* @createDate 2025-01-16 12:33:44
*/
@Service
public class IndexBooklistServiceImpl extends ServiceImpl<IndexBooklistMapper, IndexBooklist>
    implements IndexBooklistService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private IndexBooklistMapper indexBooklistMapper;
    @Autowired
    private IndexBooklistItemService indexBooklistItemService;

    /**
     * 获取书单VO
     * @param booklistId 书单id
     * @param clientRandomNumber 随机数
     * @return
     */
    @Override
    public IndexBooklistVO getIndexBooklistVO(Integer booklistId, Integer clientRandomNumber) {
        //1.获取书单对象
        IndexBooklist booklist = this.getIndexBooklistById(booklistId);
        //2.判断书单是否是换一换（随机 -> 要保证和上一轮的书籍不同）
        boolean ramdomFlag = booklist.getMoreType() == BooklistMoreTypeEnum.EXCHANGE.getValue();
        IndexBooklistVO booklistVO;
        if (ramdomFlag){
            //3.如果是随机获取
            booklistVO = this.getRandomIndexBooklistVO(booklist, clientRandomNumber);
        }else {
            //4.从缓存里获取
            String key = RedisHomepageKey.getBooklistVoKey(booklistId);
            booklistVO = this.redisService.getCache(key,IndexBooklistVO.class);
            if (booklistVO == null){
                //4.1.缓存中没有书单，从数据库获取（书单由书组成）
                List<BooklistBookVO> books = this.indexBooklistItemService.getBooklistOrderBooks(booklist.getId(), booklist.getBookIds(), booklist.getShowNumber(), booklist.getShowLikeCount());
                if (books != null){
                    //初始化
                    booklistVO = new IndexBooklistVO();
                    BeanUtils.copyProperties(booklist,booklistVO);
                    booklistVO.setBooks(books);
                    booklistVO.setRandomNumber(1);
                    //存入缓存
                    this.redisService.setExpireCache(key,booklistVO,RedisExpire.WEEK);
                }
            }

        }
        return booklistVO;
    }

    /**
     * 根据id获取书单信息
     * @param booklistId
     * @return
     */
    @Override
    public IndexBooklist getIndexBooklistById(Integer booklistId) {
        //1.判断缓存中有没有对应数据
        String key = RedisHomepageKey.getBooklistDbKey(booklistId);
        IndexBooklist booklist = this.redisService.getCache(key, IndexBooklist.class);
        if (booklist == null){
            //缓存没有 查数据库
            booklist = this.indexBooklistMapper.selectById(booklistId);
            if (booklist != null){
                //不为null，写入缓存（可以异步）
                this.redisService.setExpireCache(key,booklist, RedisExpire.WEEK);
            }

        }
        return booklist;
    }

    /**
     * 书单随机获取
     * @param booklist
     * @param clientRandomNumber
     * @return
     */
    @Override
    public IndexBooklistVO getRandomIndexBooklistVO(IndexBooklist booklist, Integer clientRandomNumber) {
        //1.搞随机数
        Random random = new Random();
        int randomNumber = random.nextInt(HomePageConstant.BOOKLIST_RANDOM_COUNT);
        if (clientRandomNumber != null) {
            //直到生成的 randomNumber 不等于 clientRandomNumber 避免重复
            while (randomNumber == clientRandomNumber) {
                randomNumber = random.nextInt(HomePageConstant.BOOKLIST_RANDOM_COUNT);
            }
        }
        //2.从缓存中获取
        String key = RedisHomepageKey.getBooklistRandomVoKey(booklist.getId());
        IndexBooklistVO booklistVO = redisService.getHashVal(key,String.valueOf(randomNumber),IndexBooklistVO.class);
        //2.1.缓存中没有，获取数据库 TODO 将随机形参 clientRandomNumber --> randomNumber
        if(booklistVO == null){
            List<BooklistBookVO> books = this.indexBooklistItemService.getBooklistRandomBooks(
                    booklist.getId(), booklist.getBookIds(), booklist.getShowNumber(),
                    randomNumber, booklist.getShowLikeCount());
            if (!books.isEmpty()){
                booklistVO = new IndexBooklistVO();
                BeanUtils.copyProperties(booklist,booklistVO);
                booklistVO.setBooks(books);
                booklistVO.setRandomNumber(randomNumber);
                //缓存到缓存
                this.redisService.setHashValExpire(key,String.valueOf(randomNumber),IndexBooklistVO.class,RedisExpire.WEEK);

            }
        }
        return booklistVO;
    }
}




